import { Store } from 'vuex'
import { State } from '..'

export const storagePlugin = (store: Store<State>) => {
	console.log('store init')

	const keyStr = localStorage.getItem('store_keys')
	const keys: string[] = keyStr ? JSON.parse(keyStr) : []
	keys.forEach((key) => {
		const storage = localStorage.getItem(key)
		store.commit(key, storage && JSON.parse(storage))
	})

	store.subscribe((mutation) => {
		// console.log(mutation, state)
		!keys.includes(mutation.type) && keys.push(mutation.type)
		localStorage.setItem(mutation.type, JSON.stringify(mutation.payload))
		localStorage.setItem('store_keys', JSON.stringify(keys))
	})
}
